package tlv.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import tlv.bean.Attr;
import tlv.bean.TlvBean;
import tlv.enums.TlvType;
import tlv.tools.TlvAbloomy;


public class AbloomyPapAuth extends Thread {
	private DatagramSocket s;
	private InetAddress hostAddress;
	private byte[] buf = new byte[1000];
	private DatagramPacket dp = new DatagramPacket(buf, buf.length);
	private int port;
	private String userIp;
	private int serialNo;
	private String mac;
	private TlvBean b = new TlvBean();
	private String username;
	private String password;

	public void run() {
		try {
			s.send(Dgram.toDatagram(ReqAuth(), hostAddress, port));
			s.receive(dp);
			b = parse(dp.getData());
			if(b.getErrCode()==0){
				System.out.println("上线成功");
			}else{
				System.out.println("上线失败");
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	/**
	 * 生成认证请求
	 * @param reqId
	 * @return
	 */
	private byte[] ReqAuth(){
		List<Attr> attr = new ArrayList<Attr>();
		Attr a = new Attr(1, username.getBytes());
		Attr b = new Attr(2, password.getBytes());
		Attr c = new Attr(238, mac2BinaryArray(mac));
		byte[] db = new byte[80];
		Attr d = new Attr(240, db);
		byte[] eb = new byte[144];
		Attr e = new Attr(241, eb);
		attr.add(a);
		attr.add(b);
		attr.add(c);
		attr.add(d);
		attr.add(e);
		return TlvAbloomy.buildAbloomy(TlvType.ReqAuth,serialNo, 0, userIp, attr);
	}

	/**
	 * 将byte[]转为TlvBean
	 * @param a
	 * @return
	 */
	private TlvBean parse(byte[] a){
		return TlvAbloomy.parse(a);
	}
	

	
	/**
	 * 将mac地址转为byte[]
	 * @param ipAdd
	 * @return
	 */
	private byte[] mac2BinaryArray(String mac) {
		byte[] binMac = new byte[6];
		String[] strs = mac.split(":");
		for (int i = 0; i < strs.length; i++) {
			binMac[i] = (byte)Integer.valueOf(strs[i],16).intValue();
		}
		return binMac;
	}
	
	/**
	 * @param ip AC的ip地址
	 * @param port AC监听的端口
	 * @param userIp 用户内网ip
	 * @param mac 用户mac地址
	 * @param username 用户名
	 * @param password 密码
	 * @param serialNo
	 */
	public AbloomyPapAuth(String ip, int port,String userIp,String mac,String username,String password,int serialNo) {
		this.port = port;
		this.userIp = userIp;
		this.serialNo = serialNo;
		this.mac = mac;
		this.username = username;
		this.password = password;
		try {
			s = new DatagramSocket();
			hostAddress = InetAddress.getByName(ip);

		} catch (UnknownHostException e) {
			System.err.println("Cannot find host");
			System.exit(1);
		} catch (SocketException e) {
			System.err.println("Can't open socket");
			e.printStackTrace();
			System.exit(1);
		}
		System.out.println("请求开始");
	}
}
